package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.*;
import cn.powertime.evaluation.facade.PersonalCenterFacade;
import cn.powertime.evaluation.service.*;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.util.CollectionUtils;
import cn.powertime.evaluation.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Facade
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class PersonalCenterFacadeImpl implements PersonalCenterFacade {

    @Autowired
    private CpsAutomaticService automaticService;
    @Autowired
    private CpsTestPaperService cpsTestPaperService;
    @Autowired
    private CpsUserCollectService userCollectService;
    @Autowired
    private CpsWrongQuestionsService wrongQuestionsService;
    @Autowired
    private DbqPostingsService postingsService;
    @Autowired
    private CpsCourseService cpsCourseService;
    @Autowired
    private DbqNewsService newsService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private DbqPostingsUserEventService dbqPostingsUserEventService;

    @Override
    public RespFocusCount count() {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();

        QueryWrapper<DbqPostingsUserEvent> qwFocus = new QueryWrapper<>();
        qwFocus.eq("type", 1);
        qwFocus.eq("user_id", userInfo.getId());
        qwFocus.eq("status", Constants.STATUS_NORMAL);
        int focusCount = this.dbqPostingsUserEventService.count(qwFocus);

        QueryWrapper<DbqPostings> qwPostings = new QueryWrapper<>();
        qwPostings.eq("user_id", userInfo.getId());
        qwPostings.eq("status", Constants.STATUS_NORMAL);
        int postingCount = this.postingsService.count(qwPostings);

        RespFocusCount focus = new RespFocusCount();
        focus.setFocusCount(focusCount);
        focus.setPostingCount(postingCount);
        return focus;
    }

    @Override
    public Page<RespPersonalPostingsListVo> personalPostingsList(PageVo vo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        Page<DbqPostings> page = new Page<>(vo.getCurrent(), vo.getSize());
        Page<RespPersonalPostingsListVo> list = this.postingsService.personalPostingsList(page, userInfo.getId());
        list.getRecords().forEach(item-> {
            Document document = Jsoup.parse(item.getContent());  //  将字符串解析成Document对象
            Elements elements = document.select("img");
            ListIterator<Element> listIterator = elements.listIterator();
            List<String> imgs = Lists.newArrayList();
            while (listIterator.hasNext()){
                imgs.add(listIterator.next().toString());
            }
            item.setImgs(imgs);
        });
        return list;
    }

    @Override
    public Page<RespFocusListVo> focusUserList(PageVo vo) {
        Page<RespFocusListVo> page = new Page<>(vo.getCurrent(), vo.getSize());
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        return this.dbqPostingsUserEventService.selectFocusList(page, userInfo.getId());
    }

    @Override
    public Page<RespPersonalPostingsListVo> collects(PageVo vo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        Page<DbqPostings> page = new Page<>(vo.getCurrent(), vo.getSize());
        Page<RespPersonalPostingsListVo> list = this.postingsService.personalCollects(page, userInfo.getId());
        list.getRecords().forEach(item-> {
            Document document = Jsoup.parse(item.getContent());  //  将字符串解析成Document对象
            Elements elements = document.select("img");
            ListIterator<Element> listIterator = elements.listIterator();
            List<String> imgs = Lists.newArrayList();
            while (listIterator.hasNext()){
                imgs.add(listIterator.next().toString());
            }
            item.setImgs(imgs);
        });
        return list;
    }

    @Override
    public IPage<DbqNews> messages(PageVo vo) {
        QueryWrapper<DbqNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.STATUS_NORMAL);
        queryWrapper.eq("type", 3);
        Page<DbqNews> page = new Page<>(vo.getCurrent(), vo.getSize());
        return this.newsService.page(page, queryWrapper);
    }

    @Override
    public IPage<WebRespCourseRecordListVo> learningRecords(PageVo vo) {
        Page<CpsCourse> page = new Page<>(vo.getCurrent(), vo.getSize());
        return cpsCourseService.recordList(page, ShiroUtils.getUserInfo().getId());
    }

    @Override
    public Page<RespAnswerTestPaperVo> answerRecord(ParamPageVo<ReqAnswerTestPaperSearchVo> vo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        Page<CpsTestPaper> page = new Page<>(vo.getPage().getCurrent(), vo.getPage().getSize());
        if (vo.getParams().getType() == 6) {
            return this.automaticService.selectAnswerRecord(page, userInfo.getId());
        } else {
            return this.cpsTestPaperService.answerRecord(page, vo.getParams(), userInfo.getId());
        }
    }

    @Override
    public RespTopicGroupVo testPaperView(Long testPaperId, Long resultId, Integer type) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        List<RespAnswerTopicListVo> list;
        if (type == 6) {
            list = this.automaticService.testPaperView(userInfo.getId(), testPaperId);
        } else {
            list = this.cpsTestPaperService.testPaperView(userInfo.getId(), testPaperId, resultId);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            RespTopicGroupVo vo = new RespTopicGroupVo();
            Map<Integer, List<RespAnswerTopicListVo>> listMap = list.stream().collect(Collectors.groupingBy(RespAnswerTopicListVo::getType));
            vo.setListMap(listMap);
            return vo;
        }
        return null;
    }

    @Override
    public Page<RespAnswerTopicListVo> collectTopicList(PageVo vo) {
        Page<RespAnswerTopicListVo> page = new Page<>(vo.getCurrent(), vo.getSize());
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        return this.userCollectService.list(page, userInfo.getId());
    }

    @Override
    public Page<RespAnswerTopicListVo> wrongTopicList(PageVo vo) {
        Page<RespAnswerTopicListVo> page = new Page<>(vo.getCurrent(), vo.getSize());
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        return this.wrongQuestionsService.list(page, userInfo.getId());
    }

    @Override
    public boolean updateUser(ReqUserUpdateVo vo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo, user);
        user.setUpdateTime(LocalDateTime.now());
        return this.userService.edit(user);
    }

}
